package com.fanjia.crm.service.impl;

import com.fanjia.crm.mapper.UserMapper;
import com.fanjia.crm.model.PageResult;
import com.fanjia.crm.model.User;
import com.fanjia.crm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by FanJia on 2020/9/20 19:22
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public User findByUsername(String username) {
        return userMapper.findByUsername(username);
    }

    @Override
    public PageResult<User> findPageResult(User user, int page, int pageSize) {
        //定义一个Map-参数先不放在map,后面再处理
        Map<String,Object> params = new HashMap<>();
        params.put("condition",user);
        params.put("start" , (page-1)*pageSize);
        params.put("length" , pageSize);
        //定义结果
        PageResult<User> result = new PageResult<>();

        result.setCount(userMapper.findCountByMap(params));
        result.setData(userMapper.findListByMap(params));
        return result;
    }

    @Override
    public void save(User user, Integer[] roleIds) {
        if(user.getId()==0){
            System.out.println("保存数据");
            userMapper.insert(user);

        }else {
            System.out.println("更改数据");
            //更新数据
            userMapper.updateUserByUser(user);

            //清空以前的用户角色
            userMapper.deleteRoleById(user.getId());
            //添加现在的用户角色

        }

        for(Integer roleId : roleIds ){
            userMapper.insertUserIdAndRoleId(user.getId(),roleId);
        }

    }

    @Override
    public User findUserAndRoleByUserId(Integer userId) {
        return userMapper.findUserAndRoleByUserId(userId);
    }
}
